package com.tuniondata.netty.common;

import java.io.IOException;
/**
 * @author yuxinchao
 */
public class Pack {

    private StringBuffer out = new StringBuffer();

    private Pack() {
    }

    public static Pack alloc() {
        return new Pack();
    }

    public Pack addData(String data) throws IOException {
        add(data);
        return this;
    }

    public Pack addInteger(Integer data, Integer length) throws IOException {
        StringBuffer pattern = new StringBuffer();
        pattern.append("%").append("0").append(length).append("d");
        add(new String(String.format(pattern.toString(), data).getBytes("GBK"), "GBK"));
        return this;
    }

    public Pack add(String data) throws IOException {
        out.append(new String(data.getBytes("GBK"), "GBK"));

        return this;
    }

    /**
     * 长度不够，右补空格
     * @param data
     * @param length
     * @return
     * @throws IOException
     */
    public Pack add(String data, Integer length) throws IOException {
        StringBuffer pattern = new StringBuffer();
        pattern.append("%1$-").append(length).append("s");
        out.append(new String(String.format(pattern.toString(), data).getBytes("GBK")));

        return this;
    }

    public byte[] pack() throws IOException {
        return out.toString().getBytes("GBK");
    }
}
